﻿using System;
using System.Windows.Forms;

namespace Smart.Navigation.Windows.Forms
{
    /// <summary>
    /// Controlビュープロバイダー
    /// </summary>
    public class ControlViewProvider : IViewProvider
    {
        private readonly Control parent;

        /// <summary>
        /// 
        /// </summary>
        public bool FitToParent { get; set; }

        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="parent">親コントロール</param>
        public ControlViewProvider(Control parent)
        {
            this.parent = parent;
            FitToParent = true;
        }

        /// <summary>
        /// 非同期
        /// </summary>
        public virtual bool IsAsync
        {
            get { return true; }
        }

        /// <summary>
        /// 非同期処理実行
        /// </summary>
        /// <param name="method">メソッド</param>
        /// <param name="args">引数</param>
        public virtual void BeginInvoke(Delegate method, params object[] args)
        {
            this.parent.BeginInvoke( method, args );
        }

        /// <summary>
        /// ビュー作成
        /// </summary>
        /// <param name="type">型</param>
        /// <returns>ビューインスタンス</returns>
        public virtual object ViewCreate(Type type)
        {
            Control view = (Control)Activator.CreateInstance( type );

            if( FitToParent )
            {
                view.Size = this.parent.Size;
            }
            this.parent.Controls.Add( view );
            if( FitToParent )
            {
                view.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
            }

            return view;
        }

        /// <summary>
        /// ビュー活性化
        /// </summary>
        /// <param name="view">ビューインスタンス</param>
        public virtual void ViewActive(object view)
        {
            Control control = (Control)view;

            control.Visible = true;
            control.Focus();
        }

        /// <summary>
        /// ビュー非活性化
        /// </summary>
        /// <param name="view">ビューインスタンス</param>
        public virtual void ViewDeactive(object view)
        {
            Control control = (Control)view;

            control.Visible = false;
        }

        /// <summary>
        /// ビュー破棄
        /// </summary>
        /// <param name="view">ビューインスタンス</param>
        public virtual void ViewDispose(object view)
        {
            Control control = (Control)view;

            this.parent.Controls.Remove( control );
            control.Parent = null;

            control.Dispose();
        }
    }
}
